'''
Created on Jul 9, 2011

@author: kafkef
'''


from PyQt4.QtGui import *
from PyQt4.QtCore import QObject, pyqtSlot, SIGNAL

from dexen.system.client import ui
from dexen.system.client.proxy import JobProxy
from dexen.system.common.base import Action


svr_proxy = ui.svr_proxy


class JobOutputPage(QWidget):       
    def __init__(self):
        QWidget.__init__(self)
        self._create_widgets()
        self.outputs = {} #job_id: output string
        self.cur_act_ids = {} #job_id: action id
        self._cur_job_id = None
        
    def _create_widgets(self):
        # Create widgets
        self._text_edit = QTextEdit()
        # Configure widgets
        self._text_edit.setReadOnly(True)
        # Layout widgets              
        layout = QVBoxLayout()
        layout.addWidget(self._text_edit)
        self.setLayout(layout)

    def update_cur_job_id(self, job_id):
        self._cur_job_id = job_id
        if not self.outputs.has_key(job_id):
            self.outputs[job_id] = ""
        if not self.cur_act_ids.has_key(job_id):
            self.cur_act_ids[job_id] = 0
            self.on_refresh()
        else:
            self._text_edit.setText(self.outputs[job_id])
    
    def on_refresh(self):
        if self._cur_job_id is None: return
        job_id = self._cur_job_id
        job_proxy = svr_proxy.get_job_cached(job_id)
        assert isinstance(job_proxy, JobProxy)
        actions = job_proxy.get_actions(self.cur_act_ids[job_id])
        # Process newly retrieved actions
        for action in actions:
            assert isinstance(action, Action)
            if action.is_receive():
                self.outputs[job_id] += action.__repr__() + "\n"
        # Save the last processed action's id
        self.cur_act_ids[job_id] = self.cur_act_ids[job_id] + len(actions)
        # Update the display based on the latest actions processed
        self._text_edit.setText(self.outputs[job_id])
        
        